package com.njust.RateMyTray_backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.njust.RateMyTray_backend.config.JwtAuthInterceptor;
import com.njust.RateMyTray_backend.common.ForbiddenException;
import com.njust.RateMyTray_backend.common.Result;
import com.njust.RateMyTray_backend.dto.LoginDTO;
import com.njust.RateMyTray_backend.dto.UserRegisterDTO;
import com.njust.RateMyTray_backend.dto.UserUpdateDTO;
import com.njust.RateMyTray_backend.entity.User;
import com.njust.RateMyTray_backend.service.UserService;
import com.njust.RateMyTray_backend.vo.LoginVO;
import com.njust.RateMyTray_backend.vo.UserProfileVO;
import com.njust.RateMyTray_backend.vo.UserRegisterVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.jsonwebtoken.Claims;

@Slf4j
@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    private User getCurrentUser() {
        Claims claims = JwtAuthInterceptor.getCurrentUserClaims();
        if (claims == null || claims.getSubject() == null) {
            throw new ForbiddenException("无法获取当前用户信息，请重新登录");
        }
        String currentUsername = claims.getSubject();
        
        User currentUser = userService.lambdaQuery().eq(User::getUsername, currentUsername).one();
        if (currentUser == null) {
            throw new ForbiddenException("无法获取当前用户信息，请重新登录");
        }
        return currentUser;
    }
    
    private void checkPermission(Long targetUserId) {
        User currentUser = getCurrentUser();
        if (!currentUser.getId().equals(targetUserId)) {
            // 可以在这里增加管理员角色的判断，以允许管理员操作
            throw new ForbiddenException("权限不足，无法操作其他用户的信息");
        }
    }

    @PostMapping("/register")
    public ResponseEntity<Result<UserRegisterVO>> register(@RequestBody UserRegisterDTO userRegisterDTO) {
        log.info("用户注册: {}", userRegisterDTO);

        User registeredUser = userService.register(userRegisterDTO);

        UserRegisterVO userRegisterVO = new UserRegisterVO();
        userRegisterVO.setUserId(registeredUser.getId());
        userRegisterVO.setUsername(registeredUser.getUsername());

        Result<UserRegisterVO> result = Result.success(201, "用户注册成功", userRegisterVO);

        return new ResponseEntity<>(result, HttpStatus.CREATED);
    }

    @PostMapping("/login")
    public ResponseEntity<Result<LoginVO>> login(@RequestBody LoginDTO loginDTO) {
        log.info("用户登录: {}", loginDTO.getUsername());

        LoginVO loginVO = userService.login(loginDTO);

        Result<LoginVO> result = Result.success(200, "登录成功", loginVO);

        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @GetMapping("/{userId}")
    public ResponseEntity<Result<UserProfileVO>> getUserProfile(@PathVariable Long userId) {
        checkPermission(userId); // 权限检查
        log.info("获取用户 {} 的个人信息", userId);

        UserProfileVO userProfile = userService.getUserProfile(userId);

        Result<UserProfileVO> result = Result.success(200, "获取用户信息成功", userProfile);

        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @PutMapping("/{userId}")
    public ResponseEntity<Result<Void>> updateUserProfile(@PathVariable Long userId, @RequestBody UserUpdateDTO userUpdateDTO) {
        checkPermission(userId); // 权限检查
        User currentUser = getCurrentUser();
        log.info("用户 {} 正在更新自己的个人信息", currentUser.getUsername());

        userService.updateUserProfile(userId, userUpdateDTO);

        Result<Void> result = Result.success(200, "用户信息更新成功", null);

        return new ResponseEntity<>(result, HttpStatus.OK);
    }
} 